package com.cms.framework.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientUtils {
	public static String doPost(String uri, Map<String,String> params) throws Exception {
		String response = null;
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(uri);
		if(params!=null && params.size() > 0){
			
			NameValuePair[] valuePairs = new NameValuePair[params.size()];
			Set<String> keySet = params.keySet();
			String key = "";
			int i = 0;
			for(Iterator<String> it = keySet.iterator();it.hasNext();i++){
				key = it.next();
				valuePairs[i] = new NameValuePair(key, params.get(key));
			}
			postMethod.setRequestBody(valuePairs);
		}
		postMethod.addRequestHeader("Content", "text/html,charset=utf-8");
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
		client.executeMethod(postMethod);
		response = getStreamString(postMethod.getResponseBodyAsStream());// 返回结果
		postMethod.releaseConnection();
		return response;
	}
	
	public static String doGet(String uriStr) throws Exception {
		
		URI uri = new URI(uriStr, true);
		GetMethod httpMethod = new GetMethod();
		httpMethod.addRequestHeader("Content-type", "text/html,charset=utf-8");
		httpMethod.setURI(uri);
		HttpClient client = new HttpClient();
		int statusCode = client.executeMethod(httpMethod);
		String responseString = "";
		if (statusCode != HttpStatus.SC_OK) {
			responseString = httpMethod.getStatusCode() + ":" + httpMethod.getStatusText();
			return responseString;
		}
		responseString = new String(httpMethod.getResponseBodyAsString().getBytes("UTF-8"));
		return responseString;
	}
	
	/**
	 * 将一个输入流转化为字符串
	 */
	private static String getStreamString(InputStream tInputStream) {
		if (tInputStream != null) {
			try {
				BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream,"utf-8"));
				StringBuffer tStringBuffer = new StringBuffer();
				String sTempOneLine = new String("");
				while ((sTempOneLine = tBufferedReader.readLine()) != null) {
					tStringBuffer.append(sTempOneLine);
				}
				return tStringBuffer.toString();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return null;
	}

}
